package com.xjoyt.pay.master.services;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.commons.TreeUtils;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.params.CompanyPageParam;
import com.xjoyt.pay.master.po.Company;
import com.xjoyt.pay.master.po.CompanyPreference;
import com.xjoyt.pay.master.repository.CompanyPreferenceRepository;
import com.xjoyt.pay.master.repository.CompanyRepository;

@Service
public class CompanyService extends AbstractService {

	@Autowired
	private CompanyRepository repository;

	@Autowired
	private CompanyPreferenceRepository companyPreferenceRepository;

	public Company get(String id) {
		return repository.findOne(id);
	}

	public ExecuteResult<Company> save(Company entity) {
		if (StringUtils.isBlank(entity.name)) {
			return ExecuteResult.fail("机构名称不能为空");
		}

		Company company = repository.findOneByName(entity.name);
		if (company != null && (StringUtils.isBlank(entity.id) || (!company.id.equals(entity.id)))) {
			return ExecuteResult.fail("机构名称重复");
		}

		if (entity.addedDate == null)
			entity.addedDate = new Date();

		if (StringUtils.isNotBlank(entity.parentId) && StringUtils.isBlank(entity.path)) {
			Company parent = repository.findOne(entity.parentId);
			if (parent != null) {
				entity.path = StringUtils.isBlank(parent.path) ? entity.parentId
						: (parent.path + TreeUtils.TREE_SPLIT + entity.parentId);
			}
		}

		entity = repository.save(entity);
		return ExecuteResult.ok(entity);
	}

	public ExecuteResult<?> delete(String id) {
		repository.delete(id);
		return ExecuteResult.ok();
	}

	public PageResult<Company> loadPage(PageParam<CompanyPageParam> param) {
		return repository.loadPage(param);
	}

	public List<Company> findAllById(String id) {
		return repository.findAllByIdOrPathLike(id, "%" + id + "%");
	}

	public List<Company> findAllParentById(List<String> ids) {
		return repository.findAllByIdIn(ids);
	}
	// public List<Company> findAllById(String id) {
	// Company entity = repository.findOne(id);
	// if (entity == null) {
	// return new ArrayList<>();
	// }
	// if (StringUtils.isBlank(entity.path)) {
	// List<Company> list = new ArrayList<>(Arrays.asList(new Company[] { entity
	// }));
	// return list;
	// }
	// String[] ids = entity.path.split(TreeUtils.TREE_SPLIT);
	// List<Company> list = repository.findAllByIdIn(ids);
	// list.add(entity);
	// return list;
	// }

	public Company getByDomain(String domain) {
		CompanyPreference preference = companyPreferenceRepository.findOneByDomain(domain);
		return preference == null ? null : preference.company;
	}
}
